package com.microtf.inscription.framework.service;

import com.microtf.inscription.framework.vo.TaskWrap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.*;

/**
 * 服务进程池运行器
 * @author guliuzhong
 * @since 1.0
 * @version 1.0
 */
@Service
@Slf4j
public class TaskService {

    /**
     * 进程任务缓存
     */
    Map<String, TaskWrap> co=new ConcurrentHashMap<>();
    String doTask(String taskName,String requestId,String name){
        switch (taskName){
            case "compressExcel":
                String taskId=taskName+"_"+requestId+"-"+name;
                TaskWrap taskWrap = co.get(taskId);
                if(taskWrap!=null){
                    return "任务已经存在";
                }
//                Future<String> stringFuture = task.compressExcel(taskName, requestId, name);
                TaskWrap taskWrap1=new TaskWrap();
                taskWrap1.setCreateDate(new Date());
//                taskWrap1.setFuture(stringFuture);
                co.put(taskId, taskWrap1);
                return "增加任务成功";
        }
        return "";
    }
    void cleanUp(){
        log.info("运行任务清理");
        co.forEach((key,value)->{
            Future<String> future = value.getFuture();
            if(future.isCancelled()){
                log.info("清理已经取消的任务{}",key);
                co.remove(key);
            }
            if(future.isDone()){
                long l = new Date().getTime() - 60000*60;
                Date date = new Date();
                date.setTime(l);
                if(value.getCreateDate().before(date)) {
                    log.info("清理已经完成的任务{}",key);
                    co.remove(key);
                }
            }
            if(!future.isDone() && !future.isCancelled()){
                long l = new Date().getTime() - 60000*60;
                Date date = new Date();
                date.setTime(l);
                if(value.getCreateDate().before(date)) {
                    log.info("清理正在进行中的任务{}，此类任务一般运行超长",key);
                    future.cancel(true);
                    co.remove(key);
                }
            }
        });
    }
    Optional<String> getTaskResult(String taskName, String requestId, String name){
        String taskId=taskName+"_"+requestId+"-"+name;
        TaskWrap taskWrap = co.get(taskId);
        if(taskWrap==null){
            return Optional.of("Not Found\r\n任务不存在。");
        }
        try {
            Future<String> future = taskWrap.getFuture();
            String s = future.get(5, TimeUnit.SECONDS);
            return Optional.of(s);
        } catch (InterruptedException e) {
            return Optional.of("PAUSE\r\n任务已中断");
        } catch (ExecutionException e) {
            return Optional.of("ERROR\r\n执行出错"+e.getMessage());
        } catch (TimeoutException e) {
            return Optional.of("RUNNING\r\n任务运行中");
        }
    }
}
